package com.exsun.gateway.jt809.master;

import com.exsun.gateway.jt809.config.NettyClientConfig;
import com.exsun.gateway.jt809.master.handler.JT809ClientInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class JT809Client {
	private final static Logger logger = LoggerFactory.getLogger(JT809Client.class);
	@Autowired
	JT809ClientInitializer jt809ClientInitializer;
	private Bootstrap bootstrap = new Bootstrap();
	private EventLoopGroup group = new NioEventLoopGroup();

	public void connect(String ip, int port)throws Exception{
		bootstrap.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress(ip, port)
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(jt809ClientInitializer);
		jt809ClientInitializer.setJT809Client(JT809Client.this);
		connect();
	}

	public void connect(){
		synchronized (bootstrap){
			logger.info("开始连接上级平台：{}", bootstrap.config().remoteAddress().toString());
			ChannelFuture channelFuture = bootstrap.connect();
			channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
				@Override
				public void operationComplete(ChannelFuture f) throws Exception {
					boolean result = channelFuture.isSuccess();
					logger.info("连接上级平台{}", result == true?"成功":"失败，开始重连！！");
					if(!result){
						//每次只定时执行一次
						channelFuture.channel().eventLoop().schedule(new Runnable() {
							@Override
							public void run() {
								connect();
							}
						}, 2, TimeUnit.SECONDS);
					}
				}
			});
		}

	}
}
